﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using XmWinKit.Models;
using System.Windows.Media;
using System.Windows.Threading;
using System.Windows.Threading;
using System.Windows.Threading;
using System.Linq;

namespace XmWinKit.Views
{
    /// <summary>
    /// ChinaCalendar.xaml 的交互逻辑
    /// </summary>
    public partial class ChinaCalendarWindow : Components.WindowSkin
    {
        private DispatcherTimer _timer;

        public ChinaCalendarModel _model { get; set; }

        public ChinaCalendarWindow()
        {
            InitializeComponent();
            _model = new ChinaCalendarModel();
            this.DataContext = _model;

            CalendarGrid.ItemsSource = _model.CalendarDays;
            YearListBox.ItemsSource = _model.Years;
            MonthListBox.ItemsSource = _model.Months;
            YearListBox.SelectedItem = _model.SelectedYear;
            MonthListBox.SelectedItem = _model.SelectedMonth;

            YearListBox.SelectionChanged += (s, e) =>
            {
                if (YearListBox.SelectedItem is int y) _model.SelectedYear = y;
            };
            MonthListBox.SelectionChanged += (s, e) =>
            {
                if (MonthListBox.SelectedItem is int m) _model.SelectedMonth = m;
            };

            // 定时器更新时间
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += (s, e) => UpdateTimeDisplay();
            _timer.Start();

            MonthPopup.Opened += MonthPopup_Opened;
        }

        private void UpdateTimeDisplay()
        {
            var now = DateTime.Now;
            CurrentTimeText.Text = now.ToString("HH:mm:ss");
            // 通知 ViewModel 刷新 CurrentDateText
            if (DataContext is ChinaCalendarModel vm)
                vm.OnPropertyChanged(nameof(vm.CurrentDateText));
        }

        private void MonthSelectButton_Click(object sender, RoutedEventArgs e)
        {
            MonthPopup.IsOpen = true;
            YearListBox.SelectedItem = _model.SelectedYear;
            MonthListBox.SelectedItem = _model.SelectedMonth;
        }

        private void ScrollToCenterOfView(ListBox listBox, object item)
        {
            if (listBox == null || item == null) return;
            
            listBox.UpdateLayout();
            var container = listBox.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement;
            if (container == null) return;
            
            var scrollViewer = FindVisualChild<ScrollViewer>(listBox);
            if (scrollViewer == null) return;

            // 计算选中项在可视区域中的位置
            double itemTop = container.TransformToAncestor(listBox).Transform(new Point(0, 0)).Y;
            double itemHeight = container.ActualHeight;
            double viewportHeight = scrollViewer.ViewportHeight;
            
            // 计算需要滚动的位置，使选中项在可视区域中居中
            double targetOffset = itemTop - (viewportHeight - itemHeight) / 2;
            
            // 确保不会滚动到负值
            targetOffset = Math.Max(0, targetOffset);
            
            // 确保不会滚动超过最大值
            double maxOffset = scrollViewer.ScrollableHeight;
            targetOffset = Math.Min(targetOffset, maxOffset);
            
            scrollViewer.ScrollToVerticalOffset(targetOffset);
        }

        // 通用VisualTree查找
        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T t)
                    return t;
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }

        private void OnAddEventClick(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("新建事项功能待实现", "提示");
        }

        private void OnTitleBarMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void CalendarDay_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (sender is Grid grid && grid.DataContext is XmWinKit.Models.CalendarDay clickedDay)
            {
                if (!clickedDay.IsCurrentMonth)
                {
                    // 跳转到该天所属的年月
                    _model.SelectedYear = clickedDay.Date.Year;
                    _model.SelectedMonth = clickedDay.Date.Month;
                    // 重新生成日历后，选中该天
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        var newDay = _model.CalendarDays.FirstOrDefault(d => d.Date == clickedDay.Date);
                        if (newDay != null)
                            _model.SelectDay(newDay);
                    }), DispatcherPriority.ApplicationIdle);
                }
                else
                {
                    _model.SelectDay(clickedDay);
                }
            }
        }

        private void MonthPopup_Opened(object sender, EventArgs e)
        {
            // 先滚动到选中项
            YearListBox.ScrollIntoView(YearListBox.SelectedItem);
            MonthListBox.ScrollIntoView(MonthListBox.SelectedItem);

            // 延迟一下，确保布局完成后再居中
            Dispatcher.BeginInvoke(new Action(() =>
            {
                var yearScrollViewer = FindVisualChild<ScrollViewer>(YearListBox);
                var monthScrollViewer = FindVisualChild<ScrollViewer>(MonthListBox);
                
                if (yearScrollViewer != null)
                {
                    yearScrollViewer.ScrollToVerticalOffset(yearScrollViewer.VerticalOffset + (yearScrollViewer.ViewportHeight/2) / 2);
                }
                if (monthScrollViewer != null)
                {
                    monthScrollViewer.ScrollToVerticalOffset(monthScrollViewer.VerticalOffset + monthScrollViewer.ViewportHeight / 2);
                }
            }), DispatcherPriority.ApplicationIdle);
        }

        private void PrevMonthButton_Click(object sender, RoutedEventArgs e)
        {
            if (_model.SelectedMonth == 1)
            {
                if (_model.SelectedYear > _model.Years.Min())
                {
                    _model.SelectedYear--;
                    _model.SelectedMonth = 12;
                }
            }
            else
            {
                _model.SelectedMonth--;
            }
        }

        private void NextMonthButton_Click(object sender, RoutedEventArgs e)
        {
            if (_model.SelectedMonth == 12)
            {
                if (_model.SelectedYear < _model.Years.Max())
                {
                    _model.SelectedYear++;
                    _model.SelectedMonth = 1;
                }
            }
            else
            {
                _model.SelectedMonth++;
            }
        }

        private void TodayButton_Click(object sender, RoutedEventArgs e)
        {
            var today = DateTime.Today;
            _model.SelectedYear = today.Year;
            _model.SelectedMonth = today.Month;

            // 选中今天
            var todayDay = _model.CalendarDays.FirstOrDefault(d => d.Date.Date == today);
            if (todayDay != null)
                _model.SelectDay(todayDay);
        }

        private void MonthListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MonthPopup.IsOpen = false;
        }
    }
}
